package org.vectrics.recruiter.struts.tag;

import java.util.Date;
import java.util.Locale;
import java.util.TreeSet;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import org.apache.ecs.html.A;
import org.apache.log4j.Category;
import org.vectrics.DataException;
import org.vectrics.SystemException;
import org.vectrics.VectricsException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.common.util.DateUtil;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.user.Interview;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.Person;
import org.vectrics.user.PersonEncounterDateComparator;

public class ScheduledInterviewsTag extends VectricsTagSupport {
	public static final long serialVersionUID = 234232352355L;
    static private Category log = Category.getInstance(ScheduledInterviewsTag.class);

	private String userId = null;
	private String contextPath = null;
	private long startTime = 0;
	private long endTime = 0;
	private int maxCount = 10;
	
	public ScheduledInterviewsTag() {
		super();
	}

	protected String getContextPath() {
		return(contextPath);
	}

	public String makeStartTag() {
		log.debug("doStartTag() called:  userId = " + getUserId());
		StringBuffer html = new StringBuffer();
		HttpServletRequest request = (HttpServletRequest)super.pageContext.getRequest();
		contextPath = request.getContextPath();
	
		Person person = null;
		if (getUserId() != null) {
			log.debug("doStartTag() finding user...");
			try {
				person = CoreServiceLocator.getPersonService().findPersonById(new Long(getUserId()));
			}
			catch (DataException de) {
				log.error("DataException finding user", de);
				throw new SystemException("DataException finding user", de);
			}
		}
		else {
			log.error("UserId property was not set.");
			throw new SystemException("UserId property was not set.");
		}
		if (person == null) {
			log.error("Could not find person Id = " + getUserId());
			throw new SystemException("Could not find person Id = " + getUserId());
		}
		
		log.debug("doStartTag() finding job canidate...");
		
		log.debug("doStartTag() - adding interview table...");
		try {
			html.append(makeInterviewTable(person, request.getLocale()).toString());
		}
		catch (VectricsException de) {
			throw new SystemException("Exception making interview table", de);
		}			
		return(html.toString());
	}
	

	private Table makeInterviewTable(Person person, Locale locale) throws VectricsException {
		log.debug("makeInterviewTable() called");
		Table table = new BorderTable();
		table.setWidth("100%");
		
		Row hdrRow = table.addRow();
        hdrRow.setDefaultBgImage(this.getContextPath() + "/site-graphics/tbl_hdr.gif");

		Cell hdrCell = hdrRow.addCell(); 
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", CoreServiceLocator.getPhraseProvider().getMessage("heading.interview.date", locale)));

		hdrCell = hdrRow.addCell(); 
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", this.getPhrase("phrase.candidate.name")));

		hdrCell = hdrRow.addCell(); 
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", this.getPhrase("prompt.interview.interviewer")));

		hdrCell = hdrRow.addCell();
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", ""));


		Date startDate = new Date(startTime);
		Date endDate = new Date(endTime);
		Date now = new Date();
		
		if (startTime == 0) {
			startDate = new Date(now.getTime() - (1 * DateUtil.MILLIS_IN_A_DAY)); 
		}
		
		if (endTime == 0) {
			endDate = null; //new Date(now.getTime() + (3* DateUtil.ONE_DAY));
		} 
		
		if (log.isDebugEnabled()) {
			log.debug("makeInterviewTable() - startDate = " + startDate);
			log.debug("makeInterviewTable() - endDate = " + endDate);
			log.debug("makeInterviewTable() - getting interview iterator");
		}
		
		TreeSet sortedInterviews = new TreeSet(new PersonEncounterDateComparator());
		
		sortedInterviews.addAll(RecruitServiceLocator.getRecruitUserService().findScheduledInterviews(startDate, endDate));
		
		Vector interviewList = new Vector();
		interviewList.addAll(sortedInterviews);
		if (interviewList.size() > 0) {
			log.debug("makeInterviewTable() - candidate has interviews");
			int count = interviewList.size();
			if (count > maxCount)
				count = maxCount;
			for (int i = count - 1; i >= 0; i--){
				log.debug("makeInterviewTable() - getting next interview for displaying in row");
				
				Interview interview = (Interview)interviewList.elementAt(i);
				if (RecruitServiceLocator.getJobProvider().isInterviewObserver(interview, person)) {
					addInterviewRow(interview, table);
				}					

			}
		}
		else {
			log.debug("makeInterviewTable() - no interviews in date range");
			Row dataRow = table.addRow();
			Cell dataCell = dataRow.addCell();
			
			dataCell.setColSpan(4);
			dataCell.addElement(TextHelper.getFont("subFont", this.getPhrase("phrase.interviews.none.scheduled")));
		}
		return(table);
	}

	private void addInterviewRow(Interview interview, Table table) throws DataException {					
		if (log.isDebugEnabled()) {
			log.debug("makeInterviewTable() - interview date = " + interview.getDateStart());
			log.debug("makeInterviewTable() - interview description = " + interview.getDescription());
			log.debug("makeInterviewTable() - interview result summary = " + interview.getStatusType().getName());
		}				
						
		Row dataRow = table.addRow();
						
		log.debug("displaying interview date & time");
		Cell cell = dataRow.addCell();
		if (interview.getDateStart() == null) {
			log.debug("makeInterviewTable - date is null");
			cell.addElement(TextHelper.getFont("subFont", "NotGiven"));
		} else {
			log.debug("makeInterviewTable - showing interview date");
			cell.addElement(TextHelper.getFont("subFont", 
					CoreServiceLocator.getDateFormat().getDateFormatRoundToMinute(
							this.getLocale()).format(interview.getDateStart())));
		}
	
		log.debug("displaying candidate's name");
		cell = dataRow.addCell();
		Person candidate = interview.getPerson();
		if (candidate != null) {
			cell.addElement(TextHelper.getFont("subFont", candidate.getName()));
		}
						
		log.debug("displaying interviewer's name");
		cell = dataRow.addCell();
		Person interviewer = interview.getLeadPerson();
		if (interviewer != null) {
			cell.addElement(TextHelper.getFont("subFont", interviewer.getName()));
		}
						
		Cell descCell = dataRow.addCell();
		log.debug("makeInterviewTable() - displaying link to interview detail");
		A link = new A();
		link.setClass("subLink");
		link.setHref(getContextPath() + "/admin/jobs/candidate/interview/edit.do?id=" + interview.getId());
		link.addElement("edit");
		descCell.addElement(link);
	}

	/**
	 * @return
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * @param userId
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	/**
	 * @return
	 */
	public long getEndTime() {
		return endTime;
	}

	/**
	 * @param endTime
	 */
	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}

}
  
